package models;

import java.util.ArrayList;
import java.util.List;

import play.data.validation.Required;
import siena.Column;
import siena.Generator;
import siena.Id;
import siena.Index;
import siena.Model;
import siena.NotNull;
import siena.Query;

public class UserProfile extends Model {
	
	@Id(Generator.AUTO_INCREMENT)
	public Long id;
	
	@NotNull
	@Required
	@Column("user_id")
	@Index("user_index")	
	public User user;
	
	@NotNull
	@Required
	@Column("profile_id")
	@Index("profile_index")
	public Profile profile;
	
	public UserProfile(User u, Profile p) {
		user = u;
		profile = p;
	}
	
	static Query<UserProfile> all() {
		return Model.all(UserProfile.class);
	}
	
	public static List<UserProfile> findAll() {
		return all().fetch();
	}
	
	
	public static List<Profile> findByUser(User user) {
		List<UserProfile> userProfiles =  all().filter("user", user).fetch();
		List<Profile> profiles = new ArrayList<Profile>();
		for(UserProfile userProfile : userProfiles) {
			profiles.add(Profile.findById(userProfile.profile.id));
		}
		return profiles;
	}
	
	public static void delete(User user) {
		all().filter("user", user).delete();
	}
	
	public static List<User> findByProfile(Profile profile) {
		List<UserProfile> userProfiles =  all().filter("profile", profile).fetch();
		List<User> users = new ArrayList<User>();
		for(UserProfile userProfile : userProfiles) {
			users.add(User.findById(userProfile.user.id));
		}
		return users;
	}
	
	public static List<User> findByProfile(Profile profile, int offset, int limit) {
		List<UserProfile> userProfiles =  all().filter("profile", profile).fetch(limit, offset);
		List<User> users = new ArrayList<User>();
		for(UserProfile userProfile : userProfiles) {
			users.add(User.findById(userProfile.user.id));
		}
		return users;
	}
	
	public static int count(Profile profile) {
		return all().filter("profile", profile).count();
	}
	
}